
// 转义字符串中的特殊字符
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

/**
 * 检测是否包含非法字符
 * @param {*} mainString 原始字符串
 * @param {*} subString 非法字符串 | 正则字符串
 * @param {*} type str | reg
 * @returns 
 */
function isHasIllegalChar(mainString, subString, type = 'str') {
    let escapedSubString;
    if (type === 'reg') {
        try {
            new RegExp(subString);  // 检查是否是合法的正则表达式
            escapedSubString = subString;
        } catch (error) {
            return { error: 'Invalid regular expression string.' };
        }
    } else {
        escapedSubString = escapeRegExp(subString);
    }
		// 构建全匹配的正则表达式 i不区分大小写 g匹配多个实例 m匹配多行字符串
    let pattern = new RegExp(`\\b${escapedSubString}\\b`, 'gim');
    let result = [];
    // 统计每个字符的信息
    if (type === 'reg') {
        let charPattern = new RegExp(escapedSubString, 'gim');
        let match;
        while ((match = charPattern.exec(mainString)) !== null) {
            let char = match[0];
            let charResult = {
                character: char,
                count: 1,
                positions: [match.index],
                contains: true
            };
            result.push(charResult);
        }
    } else {
        for (let i = 0; i < subString.length; i++) {
            let char = subString[i];
            let charResult = {
                character: char,
                count: 0,
                positions: [],
                contains: false
            };
            let charIndex = mainString.indexOf(char);
            while (charIndex !== -1) {
                charResult.count++;
                charResult.positions.push(charIndex);
                charResult.contains = true;
                charIndex = mainString.indexOf(char, charIndex + 1);
            }
            result.push(charResult);
        }
    }
    // 针对 subString 的检测结果
    let subStringResult = {
        positions: [],
        count: 0,
        contains: false
    };
    let subStringIndex = mainString.indexOf(subString);
    while (subStringIndex !== -1) {
        subStringResult.count++;
        subStringResult.positions.push(subStringIndex);
        subStringIndex = mainString.indexOf(subString, subStringIndex + 1);
    }
    subStringResult.contains = subStringResult.count > 0;
    return {
        overallResult: result,
        subStringResult: subStringResult
    };
}

export { isHasIllegalChar };